/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState } from 'react';
import { Upload, message, Image } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import { uploadFileUrl, getPublicDownloadUrl } from '@/service/common/upload';

type propsType = {
  targetAttr: number;
  imageUrl: any;
  setImageUrl: React.Dispatch<React.SetStateAction<string>>;
};
const policyUpload = (props: propsType) => {
  const { initialState } = useModel('@@initialState');
  const { fileName } = initialState || {};
  const { targetAttr, imageUrl, setImageUrl } = props;
  const [uploadLoading, setUploadLoading] = useState(false);

  const getUrl = (url: string | number) => {
    getPublicDownloadUrl([url])
      .then((result: any) => {
        if (result?.success) {
          setImageUrl(result?.data?.[0]);
        }
      })
      .catch((err: any) => {
        message.error(err);
      });
  };

  const uploadProps: any = {
    action: uploadFileUrl,
    name: { fileName },
    listType: 'picture-card',
    showUploadList: false,
    data: {
      modelName: 'insurance',
      targetAttr,
    },
    onChange(info: any) {
      setUploadLoading(true);
      if (info.file.status === 'done') {
        setUploadLoading(false);
        getUrl(info?.file?.response?.data?.id);
      }
    },
  };
  const uploadButton = (
    <div>
      {uploadLoading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传保单</div>
    </div>
  );
  return (
    <>
      <Upload {...uploadProps}>
        {imageUrl?.url ? (
          <Image width={200} src={imageUrl?.url} />
        ) : (
          uploadButton
        )}
      </Upload>
    </>
  );
};

export default policyUpload;
